import os,datetime

from utils.DBService import sqlquery

SHEBEI_SQL = """SELECT 
		departname,
		COUNT(*) AS count_star,
    SUM(CASE WHEN state = 1 THEN 1 ELSE 0 END) AS count_1,
    SUM(CASE WHEN state = 2 THEN 1 ELSE 0 END) AS count_2,
    SUM(CASE WHEN state = 3 THEN 1 ELSE 0 END) AS count_3,
    SUM(CASE WHEN state = 4 THEN 1 ELSE 0 END) AS count_4
FROM hntbhzzhuangtaiView
WHERE orgcode LIKE (    
    SELECT org_code    
    FROM t_s_depart    
    WHERE id = '{}' ) + '%'
and departname LIKE '%拌合站'
{}
GROUP BY departname;"""

def shengchansb_ovStatic(Args,user):
    print('Output参数:\n\t', Args)
    depId = Args['depId']
    dates = Args['dates']
    depId = '\',\''.join(depId.split(','))

    if depId == '8a8ab0b246dc81120146dc8180ba0017'or \
            Args['depId'] == 'All':
        depId = '8a8ab0b246dc81120146dc8180ba0017'
    elif depId == 'f6323b406b4fab1b016bacabdb9f01d3':
        depId = 'f6323b406b4fab1b016bacabdb9f01d3'
    elif depId == 'f6323b406b4fab1b016bacac674901d5':
        depId = 'f6323b406b4fab1b016bacac674901d5'
    elif depId == 'f6323b406d19fc87016d1a5c43910016':
        depId = 'f6323b406d19fc87016d1a5c43910016'
    elif depId == 'f6323b406d19fc87016d1a5b861b0014':
        depId = 'f6323b406d19fc87016d1a5b861b0014'
    else:
        depId = '8a8ab0b246dc81120146dc8180ba0017'

    dateWhere = 'and CONVERT(nvarchar(10), chuliaoshijian, 120)in (\'{}\')'
    datearray = dates.split(',')
    if len(datearray) == 2:
        dateWhere = 'and CONVERT(nvarchar(10), chuliaoshijian, 120)>=\'{}\' and CONVERT(nvarchar(10), chuliaoshijian, 120)<=\'{}\''.format(
            datearray[0], datearray[1])
    else:
        dateWhere = dateWhere.format('\',\''.join(dates.split(',')))

    banhezhanSql = SHEBEI_SQL.format(depId,dateWhere)
    print('SQL:\n\t', banhezhanSql)
    shebeiData = sqlquery(SHEBEI_SQL.format(depId,dateWhere))
    slData = []
    resdata = []
    if shebeiData.__len__() == 0:
        marktitle = '当前时间没有数据'
        return resdata,slData,marktitle
    else:
        if len(datearray) == 2:
            start = datetime.datetime.strptime(datearray[0], '%Y-%m-%d')
            end = datetime.datetime.strptime(datearray[1], '%Y-%m-%d')
            marktitle = str(start.year) + '年' + str(start.month) + '月' + str(start.day) + '日' + '到' + str(
                end.year) + '年' + str(end.month) + '月' + str(end.day) + '日' + '生产设备情况如下:'
        else:
            start = datetime.datetime.strptime(datearray[0], '%Y-%m-%d')
            marktitle = str(start.year) + '年' + str(start.month) + '月' + str(start.day) + '日' + '生产设备情况如下:'

    for shebei in shebeiData:
        if os.environ.get("ENV_NAME")=='1':
            depName,zong_count,yunx_count,yans_count,weix_count,tingy_count = \
                shebei[0],shebei[1],shebei[2],shebei[3],shebei[4],shebei[5]
        else:
            depName,zong_count,yunx_count,yans_count,weix_count,tingy_count = \
                shebei[0],shebei[1],shebei[2],shebei[3],shebei[4],shebei[5]
        slData.append([
            depName,
            zong_count,
            yunx_count,
            yans_count,
            weix_count,
            tingy_count
        ])
        resdata.append([
            depName,
            zong_count,
            yunx_count,
            yans_count,
            weix_count,
            tingy_count
        ])
    print('Data:\n\t', slData)

    a_list = []
    b_list = []
    children = []
    for item in slData:
        station_name = item[0]
        a = item[0:]
        data = {
            'key': slData.index(item),
            'departname': a[0],
            'cjpanshu': a[1],
            'cjichaobL': a[2],
            'zjpanshu': a[3],
            'zjichaobL': a[4],
            'gjpanshu': a[5]
        }
        table_head = [
            {
                "title": '站点名称',
                "dataIndex": list(data.keys())[1],
                "key": list(data.keys())[1],
            },
            {
                "title": '设备总数',
                "dataIndex": list(data.keys())[2],
                "key": list(data.keys())[2],
            },
            {
                "title": '正常工作',
                "dataIndex": list(data.keys())[3],
                "key": list(data.keys())[3],
            },
            {
                "title": '延时工作',
                "dataIndex": list(data.keys())[4],
                "key": list(data.keys())[4],
            },
            {
                "title": '未工作',
                "dataIndex": list(data.keys())[5],
                "key": list(data.keys())[5],
            },
            {
                "title": '未安装',
                "dataIndex": list(data.keys())[6],
                "key": list(data.keys())[6],
            }]
        if station_name.startswith("武黄1标"):
            a_list.append(data)
        else:
            b_list.append(data)
    if len(a_list)>0:
        add_totals(a_list)
        childrenA_Data = {"children":[{"title": '武黄1标拌合站', "data": {"tableHead": table_head, "tableBody": a_list}}] ,"title": '武黄1标'}
        children.append(childrenA_Data)
    if len(b_list)>0:
        add_totals(b_list)
        childrenB_Data = {"children":[{"title": '武黄2标拌合站', "data": {"tableHead": table_head, "tableBody": b_list}}] ,"title": '武黄2标'}
        children.append(childrenB_Data)

    result = [{"title": "武黄高速", "children": children}]

    print("result:\n\t",result)
    return resdata,result,marktitle;

def add_totals(data):
    # 计算合计值
    total_cjichaobL = sum(item["cjichaobL"] for item in data)
    total_zjpanshu = sum(item["zjpanshu"] for item in data)
    total_cjpanshu = sum(item["cjpanshu"] for item in data)
    total_zjichaobL = sum(item["zjichaobL"] for item in data)
    total_gjpanshu = sum(item["gjpanshu"] for item in data)

    # 添加合计项
    total_item = {
        "cjichaobL": total_cjichaobL,
        "cjpanshu": total_cjpanshu,
        "departname": "合计",
        "key": "",
        "zjpanshu": total_zjpanshu,
        "zjichaobL":total_zjichaobL,
        "gjpanshu":total_gjpanshu
    }

    data.append(total_item)

    return data

functionConf = {
    "name": "shengchansb_ovStatic",
    "description": "key point:生产设备。Query the device status by ID and time",
    "parameters": {
        "type": "object",
        "properties": {
            "depId": {
                "type": "string",
                "description": "Department IDs.Department IDs. 武黄1标是(f6323b406b4fab1b016bacabdb9f01d3).武黄2标是(f6323b406b4fab1b016bacac674901d5).If you ask project A, the default return is project A high speed"
            },
            "dates": {
                "type": "string",
                "description": "Date(s) of material production in yyyy-MM-dd format. Use comma-separated values (e.g., '2023-07-14,2023-07-15')."
            }
        },
        "required": [
            "depId",
            "dates"
        ]
    }
}
